﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

using Autofac;
using FluentValidation.Mvc;
using System.Threading;
using System.IO;

namespace Presentation.Web.Admin
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明，
    // 请访问 http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        static Timer autoPushTimer = null;

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{resource}.jpg/{*pathInfo}");
            routes.IgnoreRoute("{resource}.gif/{*pathInfo}");
            routes.IgnoreRoute("{resource}.bmp/{*pathInfo}");
            routes.IgnoreRoute("{resource}.png/{*pathInfo}");

            PreAdminRoute.Register(routes);
            routes.MapRoute(
                "Default", // 路由名称
                "{controller}/{action}/{id}", // 带有参数的 URL
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }, null,
                new string[] { "Presentation.Web.Admin.Controllers" }
            );
        }

        protected void Application_Start()
        {
            if (PreAdminConfigSettingService.IsAddAutoPushTextLog)
            {
                var message = "应用程序开始..............." + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                Infrastructure.Data.Uow.Log.LoggerRepositoryManager.AddLogInfo(message);
            }
            AreaRegistration.RegisterAllAreas();
            var builder = new Autofac.ContainerBuilder();
            PreAdminIoc.Register(builder);
            builder.RegisterType<Presentation.Web.Admin.PushNoteService>();
            var container = builder.Build();
            var dependency = new Autofac.Integration.Mvc.AutofacDependencyResolver(container);
            DependencyResolver.SetResolver(dependency);

            PreAdminMapping.Map();
            //模型验证
            FluentValidationModelValidatorProvider.Configure();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            AutoResetEvent autoEvent = new AutoResetEvent(false);
            //启动定时推送的一个唯一实例
            var pushTimer = Infrastructure.Crosscutting.Comm.Service.SingletonService<Presentation.Web.Admin.TimerPushService>.Instance;
            var intervalTime = PreAdminConfigSettingService.AutoPushTimerNum * 60 * 1000;
            //var intervalTime =  5 *60 * 1000;
            if (pushTimer != null)
            {
                TimerCallback tcb = new TimerCallback(pushTimer.TimerPush);
                autoPushTimer = new Timer(tcb, autoEvent, 20000, intervalTime);
            }
        }

        protected void Application_End()
        {
            if (autoPushTimer != null)
            {
                autoPushTimer.Dispose();
            }
            if (PreAdminConfigSettingService.IsAddAutoPushTextLog)
            {
                var message = "应用程序结束..............." + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                Infrastructure.Data.Uow.Log.LoggerRepositoryManager.AddLogInfo(message);
            }

            //程序被回收的时候，激活程序,貌似不怎么好使
            //那就每10分钟访问一次login页面
            //在timer里面执行的
            var configPath = System.IO.Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "web.config");
            File.SetLastWriteTimeUtc(configPath, DateTime.Now);
            Thread.Sleep(30 * 1000);
            var url = "http://imap.ipow.cn/login/";
            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                var res = client.DownloadString(url);
            }
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            if (!HttpContext.Current.IsCustomErrorEnabled)
            {
                return;
            }
            var error = Server.GetLastError();
            var httpException = new HttpException(null, error);

            if (PreAdminConfigSettingService.IsAddAutoPushTextLog)
            {
                Infrastructure.Data.Uow.Log.LoggerRepositoryManager.AddLogInfo(error.InnerException != null ? error.InnerException.Message : error.Message);
            }

            var errorControllerName = error.TargetSite.DeclaringType.FullName;
            var errorActionName = error.TargetSite.Name;
            Server.ClearError();
            var routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", "index");
            routeData.Values.Add("httpException", httpException);
            routeData.Values.Add("controllerName", errorControllerName);
            routeData.Values.Add("actionName", errorActionName);
            var errorController = ControllerBuilder.Current.GetControllerFactory().CreateController(
                new RequestContext(new HttpContextWrapper(Context), routeData), "Error");
            errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
        }
    }
}